import {
  Controller,
  Post,
  Body,
  Get,
  Put,
  Param,
  ParseIntPipe,
  Delete,
  Patch,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CommonObjectProps, CommonResponse } from '../typings';
import { responseWrapper } from '../utils';

@Controller('users')
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  @Post()
  async createUser(@Body() data: CommonObjectProps): Promise<CommonResponse> {
    try {
      const res = await this.userService.createUser(data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async userList(): Promise<CommonResponse> {
    try {
      const res = await this.userService.userList();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getUser(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.user(id);
      if (!res) throw new Error('用户不存在');
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Put(':id')
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: CommonObjectProps,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.update(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async delete(
    @Param('id', new ParseIntPipe()) id: number,
  ): Promise<CommonResponse> {
    try {
      const res = await this.userService.delete(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Patch(':id')
  async assginRole(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() role: CommonObjectProps,
  ) {
    // 分配角色
    try {
      const res = await this.userService.assginRole(id, role);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
